//
//  WechatPayHelper.m
//  client
//
//  Created by WangErdong on 2017/8/5.
//
//

#import "WechatPayHelper.h"
#import<CommonCrypto/CommonDigest.h>
#import "WXApi.h"
#import "Constant.h"

@implementation WechatPayHelper

+ (void)pay:(NSDictionary *)dict {
    
    // 应用ID
    NSString *appid = kWechatAppid;
    // 商户号
    NSString *partnerid = kWechatPartnerid;
    // 预支付交易会话ID
    NSString *prepayid = dict[@"prepayid"];
    // 扩展字段
    NSString *packageValue = @"Sign=WXPay";
    // 随机字符串
    NSString *noncestr = [WechatPayHelper generateNonceString];
    // 时间戳
    UInt32 timestamp = [[NSDate date] timeIntervalSince1970];
    // 要加密的字符串
    NSString *encryString = [NSString stringWithFormat:@"appid=%@&noncestr=%@&package=%@&partnerid=%@&prepayid=%@&timestamp=%u&key=%@", appid, noncestr, packageValue, partnerid, prepayid, (unsigned int)timestamp, kWechatSecretkey];
    
    // 签名
    NSString *sign = [WechatPayHelper generateSign:encryString];
    
    PayReq *request = [[PayReq alloc] init];
    request.partnerId = partnerid;
    request.prepayId = prepayid;
    request.package = packageValue;
    request.nonceStr = noncestr;
    request.timeStamp = timestamp;
    request.sign = sign;

    [WXApi sendReq:request];
}

+ (NSString *)generateNonceString {

    static int kNumber = 32;
    
    NSString *sourceStr = @"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    NSMutableString *resultStr = [[NSMutableString alloc] init];
    srand((unsigned)time(0));
    for (int i = 0; i < kNumber; i++)
    {
        unsigned index = rand() % [sourceStr length];
        NSString *oneStr = [sourceStr substringWithRange:NSMakeRange(index, 1)];
        [resultStr appendString:oneStr];
    }

    return resultStr;
}

+ (NSString *)generateSign:(NSString *)string {
    
    NSString *sign = [self MD5ForUpper32Byte:string];

    return sign;
}

+ (NSString *)MD5ForUpper32Byte:(NSString *)str {
    
    //要进行UTF8的转码
    const char* input = [str UTF8String];
    unsigned char result[CC_MD5_DIGEST_LENGTH];
    CC_MD5(input, (CC_LONG)strlen(input), result);
    
    NSMutableString *digest = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
    for (NSInteger i = 0; i < CC_MD5_DIGEST_LENGTH; i++) {
        [digest appendFormat:@"%02X", result[i]];
    }
    
    return digest;
}

@end
